<?php
/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2019/3/14
 * Time: 15:24
 */
namespace app\admin\controller;

use app\AdminData\ProxyShopData;
use app\common\Common;
use think\Config;
use think\Db;
use think\Request;
use think\Session;

class ProxyShop extends Base
{
    public function checkProxyShop($img, $address, $business_license, $proxy_name)
    {
        $count = count($img);
        if ($count > 10) {
            return ['code' => $this->f_code, 'msg' => '资质图片不能超过10张'];
        }
        $len = mb_strlen($address);
        if ($len > 100) {
            return ['code' => $this->f_code, 'msg' => '地址长度过长,请控制在100字内'];
        }
        $len = strlen($business_license);
        if ($len > 18 || $len < 15) {
            return ['code' => $this->f_code, 'msg' => '营业执照错误'];
        }
        $len = mb_strlen($proxy_name);
        if ($len > 40) {
            return ['code' => $this->f_code, 'msg' => '名称长度不能超过40个字'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 添加渠道商户
     * @param $name
     * @param $pwd
     * @param $img
     * @param $address
     * @param $business_license
     * @param $proxy_name
     * @return \think\response\Json
     */
    public function addProxyShop($name,$pwd, array $img,$address, $business_license, $proxy_name,$portrait_img,$portrait_phone,$area_id)
    {
        $len = mb_strlen($name);
        if ($len < 4 || $len > 18) {
            return json(['code' => $this->f_code, 'msg' => '账号长度4-18位']);
        }
        $len = mb_strlen($pwd);
        if ($len != 32) {
            return json(['code' => $this->f_code, 'msg' => '密码填写错误']);
        }
        $res = $this->checkProxyShop($img, $address, $business_license, $proxy_name);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (Common::checkTableFields('drh_proxy_shop_account', 'account_name', $name) == $this->t_code) {
            return json(['code' => $this->f_code, 'msg' => '账号以存在']);
        }
        $time = time();
        $pd = new ProxyShopData();
        Db::startTrans();
        $id = $pd->addProxyShop($name, $pwd, $time);
        if ($id) {
            $info = $this->addProxyShopInfo($id, $img, $address, $business_license, $proxy_name,$portrait_img,$portrait_phone,$area_id, $pd);
            if ($info) {
                Db::commit();
                return $info;
            }
        }
        Db::rollback();
        return json(['code' => $this->f_code, 'msg' => '网络连接错误,请稍后在试!']);
    }

    public function addProxyShopInfo($user_id, $img, $address, $business_license, $proxy_name,$portrait_img,$portrait_phone,$area_id, ProxyShopData $pd)
    {
        $res = $pd->addProxyShopInfo($user_id, $img, $address, $business_license, $proxy_name,$portrait_img,$portrait_phone,$area_id);
        $data = md5(time()+rand(1,9999));
        cache($data,$res);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '注册成功!', 'data' =>$data]);
        } else {
            return json(['code' => $this->f_code, 'msg' => '注册失败']);
        }

    }

    /**
     * 渠道商户登陆
     * @param $name
     * @param $pwd
     * @return \think\response\Json
     */
    public function loginProxyShop($name, $pwd)
    {
        $tel = Common::getTableValue('drh_proxy_shop_account', 'id', ['account_name', 'account_pwd'], [$name, $pwd]);
        if (empty($tel)) {
            return json(['code' => $this->f_code, 'msg' => '账号密码错误']);
        }
        $data = md5(time()+rand(1,9999));
        cache($data,$tel);
        return json(['code' => $this->t_code, 'msg' => '登陆成功!','data' =>$data]);
    }
    //代理商数据
    public function Proxy_data($data){
        if(empty(cache($data))){
            return json(['code'=>$this->f_code,'msg'=>"ok"]);
        }
            //渠道商数量
        $array['number'] = Common::db_count("COUNT(id)","`count`","drh_proxy_shop_account")[0]['count']??0;
            //产品数量
        $array['quantity'] = Common::db_count("COUNT(id)","`count`","drh_proxy_ware")[0]['count']??0;
            //平台累计出货量
        $ship = implode(",",Common::er_array(Common::db_count("goods_id","","drh_goods_proxy")));
        $shop_goods = implode(",",Common::er_array(Common::db_count("id","","drh_goods","is_ware=1 AND id IN(".$ship.")")));//
        $shop_order =Common::db_count("price,goods_num","","drh_goods_order","goods_id IN(".$shop_goods.")");//Common::er_array();
        $goods_num = array();
        $price = array();
        foreach ($shop_order as $key =>$val){
            $price[] = $val['price'];
            $goods_num[] = $val['goods_num'];
        }
        $array['cumulative_shipment'] =array_sum($goods_num);
            //今日出货量
        $array['volume_today'] =array_sum(Common::er_array(Common::db_count("goods_num","","drh_goods_order","order_start_time>".Common::getTime("d")." AND goods_id IN(".$shop_goods.")")));
            //累计成交金额
        $array['knockdown'] =  array_sum($price);
            return json(['code'=>$this->t_code,'msg'=>"ok",'data'=>$array]);
    }
    /*
     * 渠道商与分类信息
     * */
    public function Agent_information($data){
        $id = cache($data);
        if(empty($id))return json(['code'=>$this->f_code,'msg'=>"无效"]);
        //代理商信息
        $info = Common::db_count("*","","drh_proxy_shop_info","user_id=".$id." AND recover_status=0 AND verify_status=1");
        if($info == array()) return json(['code'=>$this->f_code,'msg'=>"商户信息不存在或商户未审核"]);
        $array['info'] = $info[0]??[];
        $array['info']['img'] = json_decode($array['info']['img'],true)??unserialize($array['info']['img']);
        //分类信息
        $array['class'] = Db::query("SELECT `class_name`,id,Channel_commodity_id FROM drh_proxy_classification WHERE account_id=".$id);
        $channel= array();
        $cumulative = array();
        foreach ($array['class'] as $key=>$val){
            $channel[]= count(array_filter(explode(',',$val['Channel_commodity_id'])));
            $cumulative[] = array_filter(explode(',',$val['Channel_commodity_id']));
        }
//        产品数量
        $array['info']['count'] = array_sum(array_filter($channel));
        foreach ($cumulative as $key=>$val){
          $cumulative[$key] = implode(',',$val);
        }
        $order = Db::name('drh_goods_order')->where('pay_status',2)->where('goods_id','in',implode(',',$cumulative))->field('goods_num,price')->select();
        //累计出货量
        $array['info']['cumulative_shipment'] = Common::summation($order,'goods_num');
        //今日出货量
        $shipment_time = Common::getTime('d');
        $array['info']['shipment_volume_today'] =Common::summation(Db::name('drh_goods_order')->where('pay_status',2)->where('goods_id','in',implode(',',$cumulative))->where('ship_time','>',$shipment_time)->field('goods_num')->select(),'goods_num');//  Common::er_array(Db::query("SELECT count(id) as `count` FROM drh_goods_order WHERE goods_id IN ('{$channel}') AND pay_status=2 AND ship_time>'{$shipment_time}'"))[0]??0;
        //累计金额
        $array['info']['accumulated_money'] = Common::summation($order,'price');
        return json(['code'=>$this->t_code,'msg'=>"ok",'data'=>$array]);
    }
    /*
     * 商品信息
     * */
    public function wares($data,$id=-1,$page=1,$pagetwo=5){
        $data_id = cache($data);
        if($data_id=="")return json(['code'=>$this->f_code,'msg'=>"无效"]);
        if($id == -1){
            $ware_id = Common::db_count('Channel_commodity_id',"id","drh_proxy_classification","account_id={$data_id}")["0"]['id']??null;
        }else{
            $ware_id = Common::db_count('Channel_commodity_id',"id","drh_proxy_classification","account_id={$data_id} AND id=".$id)["0"]['id']??null;
        }
        $ware_id = implode(",",array_filter(explode(',',$ware_id)));
        if(empty($ware_id)) return json(['code'=>$this->t_code,'msg'=>"ok",'data'=>[]]);
        $b = ($page-1)*$pagetwo;
        $wares = Db::table("drh_goods")->where('id',"in",$ware_id)->where('is_shelves',1)->limit($b,$pagetwo)->select();
        $total = Db::table("drh_goods")->where('id',"in",$ware_id)->where('is_shelves',1)->count();
        foreach ($wares as $k=>$v){
            $wares[$k]['goods_img'] = json_decode($v['goods_img'])??unserialize($v['goods_img']);
            $wares[$k]['goods_attr_value'] = json_decode($v['goods_attr_value'])??unserialize($v['goods_attr_value']);
            $wares[$k]['goods_info'] = json_decode($v['goods_info'])??$v['goods_info'];
        }

        $data = [
            'list'=>$wares,
            'total'=> $total
        ];
        return json(['code'=>$this->t_code,'msg'=>"ok",'data'=>$data]);
    }
    /*
     * 新增分类
     * */
    public function add_classification($data,$name){
        $id = cache($data);
        $cation = count(Common::db_count('id',"","drh_proxy_classification","class_name='".$name."' AND account_id=".$id));
        if($cation>1){
            return json(['code'=>$this->f_code,'msg'=>"当前分类已存在"]);
        }
        $add_id =Common::db_insert('drh_proxy_classification',['class_name'=>$name,'account_id'=>$id]);
        if($add_id){
            return json(['code'=>$this->t_code,'msg'=>"ok"]);
        }else{
            return json(['code'=>$this->f_code,'msg'=>"添加失败"]);
        }
    }
    public function del_classification($classification_id){
        Db::startTrans();
        try{
            Db::execute('DELETE FROM drh_proxy_classification WHERE id='.$classification_id);
            Db::commit();
            return json(['code'=>$this->t_code,'msg'=>'OK']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['code'=>$this->f_code,'msg'=>$e->getMessage()]);
        }
    }
    //渠道商品添加
    public function commodity(Request $request){
        $goods = $request->param();
        unset($goods['jurisdiction']);
        unset($goods["/admin/proxyshop/proxy/commodity"]);
        $class_id = $goods['id'];
        unset($goods['id']);
        if(!is_array($goods['price'])){
            return json(['code'=>$this->f_code,'msg'=>"属性参数错误"]);
        }
        $goods['goods_attr_value'] = serialize($goods['price']);
        $goods['goods_img'] = serialize($goods['goods_img']);
        unset($goods['shuxin']);
        unset($goods['price']);
        if(!empty($goods['amend_id'])){
           $amend_id =  $goods['amend_id'];
           unset($goods['amend_id']);
            Db::startTrans();
            try{
              $amend = Db::execute("UPDATE drh_goods SET goods_name='{$goods['goods_name']}',goods_img='{$goods['goods_img']}',goods_price='{$goods['goods_price']}',buying_price='{$goods['buying_price']}',goods_info='{$goods['goods_info']}',lightspot='{$goods['lightspot']}',rebates='{$goods['rebates']}',goods_attr_value='{$goods['goods_attr_value']}'  WHERE id={$amend_id}");
                if($amend==1){
                    Db::commit();
                    return json(['code'=>$this->t_code,'msg'=>"OK"]);
                }else{
                    return json(['code'=>$this->f_code,'msg'=>"参数未修改"]);
                }
            }catch (\Exception $e){
                Db::rollback();
                return json(['code'=>$this->t_code,'msg'=>$e->getMessage()]);
            }
        }else{
            $goods['create_time'] = time();
            $goods['is_ware'] =1;
            $id = Common::db_insert("drh_goods",$goods);
            if($id){
                $class  = Common::db_count("Channel_commodity_id","","drh_proxy_classification","id=".$class_id)[0]["Channel_commodity_id"]??null;
                $class = explode(',',$class);
                array_push($class,$id);
                $class = implode(',',$class);
                Db::startTrans();
                try{
                    if(Common::db_upload("drh_proxy_classification","Channel_commodity_id='".$class."' WHERE id=".$class_id)){
                        Db::commit();
                        return json(['code'=>$this->t_code,'msg'=>"ok"]);
                    }
                }catch (\Exception $e){
                    Db::rollback();
                    return json(['code'=>$this->f_code,'msg'=>$e->getMessage()]);
                }
            }else{
                return json(['code'=>$this->f_code,'msg'=>"添加失败"]);
            }
        }
    }
    public function modify_classification($goods_id,$classification_id){
            Db::startTrans();
            try{
                $class = Common::db_count("id,Channel_commodity_id","","drh_proxy_classification","Channel_commodity_id LIKE '%{$goods_id}%'")[0]??array();
                $commodit_id = array_filter(explode(',',$class['Channel_commodity_id']));
                foreach ($commodit_id as $key=>$value){
                    if($value == $goods_id){
                        unset($commodit_id[$key]);
                    }
                }
                $commodit_id = implode(',',$commodit_id);
                Common::db_upload("drh_proxy_classification","Channel_commodity_id='{$commodit_id}' WHERE id={$class['id']}");

                $proxy = Common::db_count("id,Channel_commodity_id","","drh_proxy_classification","id={$classification_id}")[0]??array();
                $proxy_id = array_filter(explode(',',$proxy['Channel_commodity_id']));
                array_push($proxy_id,$goods_id);
                $proxy_id = implode(',',$proxy_id);
                Common::db_upload("drh_proxy_classification","Channel_commodity_id='{$proxy_id}' WHERE id={$classification_id}");
                Db::commit();
                return json(['code'=>$this->t_code,'msg'=>"ok"]);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code'=>$this->f_code,'msg'=>$e->getMessage()]);
            }


    }
    //修改商品详情
    public function goods_change($id){
            $good = Common::db_count('id,goods_name,goods_price,goods_img,goods_attr_value,buying_price,goods_info,lightspot,rebates',"","drh_goods","is_ware=1 AND id=".$id)[0]??null;
            $good['classification_id'] = Common::db_count("id","","drh_proxy_classification","Channel_commodity_id like '%{$good['id']}%'")[0]['id']??-1;
            $good['goods_attr_value'] = unserialize($good['goods_attr_value']);
            $good['goods_img'] = unserialize($good['goods_img']);
            return json(['code'=>$this->t_code,'msg'=>"ok","data"=>$good]);
    }
    //供货商
    public function material($mat_id,$type=0,$page=1,$pre=100){
        $b = ($page-1)*$pre;
        $mater = array_filter(Common::er_array(Common::db_count("Channel_commodity_id","","drh_proxy_classification","account_id=".$mat_id)));
        $mat = array();
        foreach ($mater as $k=>$v){
          $mat[] = array_filter(explode(",",$v));
        }

        if($mat == array()){
                $mat = -1;
        }else{
           $mat =  implode(',',Common::er_array($mat));
        }
//        $order = Common::db_count("a.id,a.order_num,a.address,a.freight_num,c.user_name,c.user_tel","","drh_goods_order as a left join drh_goods as b ON b.id=a.goods_id left join drh_user_info as c on a.user_id=c.id","a.goods_status={$type} and a.goods_id in('".$mat."')  LIMIT {$b},{$pre}");
        $order = Db::name('drh_goods_order a')->join('drh_goods b','b.id=a.goods_id','left')->join('drh_user_info c','a.user_id=c.id','left')->where('a.goods_status',$type)->where('a.goods_id','in',$mat)->field('a.id,a.order_num,a.address,a.freight_num,c.user_name,c.user_tel')->limit($b,$pre)->select();
        foreach ($order as $k=>$v){
            $order[$k]['address'] = json_decode($v['address']);
            $order[$k]['address']->create_time = date("Y-m-d H:i:s",$order[$k]['address']->create_time);
        }
        return json(['code'=>$this->t_code,'msg'=>"ok","data"=>[
            'list'=>$order,
            'total'=>Db::name('drh_goods_order a')->join('drh_goods b','b.id=a.goods_id','left')->join('drh_user_info c','a.user_id=c.id','left')->where('a.goods_status',$type)->where('a.goods_id','in',$mat)->count()
        ]
        ]);
    }

    //所有区域
    public function china_area(){
        $china_area = unserialize(cache("china_area"));
        if($china_area == ""){
            $china_area = Common::db_count("*","","china_area");
            $china_area = Common::get_attr($china_area,0);
            cache("china_area",serialize($china_area));
        }
        return json(['code'=>$this->t_code,'msg'=>"ok","data"=>$china_area]);
    }
    //区域数据
    public function region($id){
//        cache("regiom_".$id,null);
//        echo 1;
//        exit;
        $array = unserialize(cache("regiom_".$id));
        if($array == ""){
            $regin =  Common::db_count("id,name  ","","china_area","id=".$id)[0]??array();
            if($regin == array())  return json(['code'=>$this->f_code,"msg"=>"无当前城市"]);
            $regin['name'] = mb_substr($regin['name'],0,2,"utf-8");
            $user = Common::db_count("id,user_name,user_integral","","drh_user_info","user_lv=1 AND city LIKE '%".$regin['name']."%'");
            $member = Common::db_count("id,user_name,user_integral","","drh_user_info","user_lv=2 AND city LIKE '%".$regin['name']."%'");
            //代理商数量
            $array['number_of_agents'] = Common::db_count_id("COUNT(id)","count","drh_proxy_shop_info","area_id=".$regin['id']);
            //创始会员数量
            $array['user_info'] = count($user);
            //交子数量
            $array['jiaozi'] = Common::summation($user,"user_integral");
            $shop_id = implode(",",Common::er_array(Common::db_count("shop_id","","drh_shop_city"," city LIKE '%".$regin['name']."%'")));
            if($shop_id== ""){
                $store = array();
                $turnover_id = -1;
            }else{
                $store = Common::db_count("id","","drh_shop","id IN(".$shop_id.")");
                $turnover_id = implode(",",Common::er_array($store));
            }
            //店铺数量
            $array['shop_number'] = count($store);
            //当月店铺营业额
            $array['turnover'] = Common::summation(Common::db_count("price","","drh_goods_order","order_start_time>".Common::getTime("m")." AND shop_id IN('".$turnover_id."')"),"price");
            if($user == ""){
                $column = -1;
            }else{
                $column =  implode(",",array_column($user,"id"));

            }
            //当月交子质押数量
            $array['pledge'] =   Common::summation(Common::db_count("integral","","drh_integral_withdraw","create_time>".Common::getTime("m")." AND user_id IN('".$column."')"),"integral");
            //会员数量
            $array['member'] = count($member);
            //总金额

            if($member == array()){
                $member_column = -1;
            }else{
                $member_column = implode(",",array_column($member,"id"));
            }
            $price = Common::db_count("price","","drh_goods_order","order_start_time>".Common::getTime("m")." AND user_id IN(".$member_column.")");

            //当月交易手续费
            $array['deal'] = bcmul(array_sum(Common::er_array($price)),0.01)+bcmul(array_sum(Common::er_array($price)),0.006);
            //当月交子盈利
            $array['gain'] = bcmul(array_sum(Common::er_array($price)),0.01);
            cache("regiom_".$id,serialize($array),10800);
        }
        return json(['code'=>$this->t_code,"msg"=>"ok","data"=>$array]);
    }
    //区域详情
    public function details($id){

        $array =   unserialize(cache("details".$id));

      if($array == array()) {

          $regin = Common::db_count("id,name  ", "", "china_area", "id=" . $id)[0]??array();
          if ($regin == array()) return json(['code' => $this->f_code, "msg" => "无当前城市"]);
          $regin['name'] = mb_substr($regin['name'], 0, 2, "utf-8");
          $parameter = unserialize(Common::db_count_id("merchant_and_commission", "para", "drh_parameter"));

          //交子参数设置
          $copulation = unserialize(Common::db_count_id("copulation", "copulation", "drh_parameter"));
          //当前城市创始会员ID
          $user = implode(",", Common::er_array(Common::db_count("id", "", "drh_user_info", "user_lv=1 AND city LIKE '%" . $regin['name'] . "%'")));
          if($user == "")$user=-1;

          //用户总金额
          $user_money = Common::db_count("integral,append_integral", "", "drh_original_member", "user_id IN(" . $user . ")");

          $array['initiate']['money'] = bcadd(Common::summation($user_money, "integral"), Common::summation($user_money, "append_integral"));

          //奖励配股
          $array['initiate']['rights_issue'] = bcdiv($array['initiate']['money'], 2);
          //推荐配股
          $array['initiate']['shares'] = Common::summation(Common::db_count("recommend_integral", "", "drh_original_member", "user_id IN(" . $user . ")"), "recommend_integral");
          //推荐配股质押(积分)
          $array['initiate']['pledge'] = Common::summation(Common::db_count("integral", "", "drh_integral_withdraw_flow", "user_id IN(" . $user . ")"), "integral");
          //奖励配股应急数量

          $array['initiate']['emergency_number'] = Common::summation(Common::db_count("money", "", "drh_original_recommend_integral_withdraw", "user_id IN(" . $user . ")"), "money");
          //累计收益
          $array['initiate']['grand_total'] = bcadd($array['initiate']['rights_issue'], $array['initiate']['shares']);

          //实体店铺数量
          $array['commercial_tenant']['entity'] = Common::db_count_id("COUNT(id)", "count", "drh_user_info", "user_lv=5 AND city LIKE '%" . $regin['name'] . "%'");

          //当前城市网店id
          $online_id = implode(",", Common::er_array(Common::db_count("shop_id", "", "drh_shop_city", "city_id=" . $id)));
          if($online_id == "")$online_id=-1;
          //网店数量

          $array['commercial_tenant']['online_store'] = Common::db_count_id("COUNT(id)", "count", "drh_shop", "id IN(" . $online_id . ")");
          //当前累计营业总额
          $array['commercial_tenant']['business_turnover'] = round(Common::summation(Common::db_count("price", "", "drh_goods_order", "shop_id IN(" . $online_id . ")"), "price"));
          //平台交易手续费收入
          $array['commercial_tenant']['service_charge'] = bcmul($array['commercial_tenant']['business_turnover'], 0.01);
          //平台年服务费收取
          $charge = array_count_values(Common::er_array(Common::db_count("shop_id", "", "drh_goods_order", "shop_id IN(" . $online_id . ")")));
          if($charge == array()){
              $single =array();
          }else{
              foreach ($charge as $k => $v) {
                  if ($v > $parameter['amount']) {
                      $single[] = $k;
                  }else{
                      $single[] ="";
                  }
              }
          }
          $array['commercial_tenant']['cover_charge'] = round(bcmul(count($single), $parameter['service_charge']));

          //店铺推荐人奖励
          $drh_shop = implode(",", Common::er_array(Common::db_count("user_id", "", "drh_shop", "id IN(" . $online_id . ")")));
          if($drh_shop == "")$drh_shop=-1;

          $array['commercial_tenant']['referrer'] = bcmul(bcmul(array_sum(Common::er_array(Common::db_count("price", "", "drh_goods_order", "shop_id IN(" . $drh_shop . ")"))), 0.01), 0.1);
          //店铺推荐人佣金

          $referr = Common::db_count("*", "", "drh_user_friend", "friend_id IN(" . $drh_shop . ")");
          $frequency = count($referr);
          $para = $parameter['brokerage'] ?? 0;
          $array['commercial_tenant']['commission'] = bcmul($frequency, $para);

          //该地区平台运营支出
          $array['commercial_tenant']['monthly_expense'] = bcmul($array['commercial_tenant']['online_store'], config("monthly_expense"));
          //平台毛利
          $array['commercial_tenant']['gross_margin'] = bcsub(bcadd($array['commercial_tenant']['service_charge'], $array['commercial_tenant']['cover_charge']), bcadd($array['commercial_tenant']['referrer'], $array['commercial_tenant']['commission']));
          //交子数量

          $initiate = array_count_values(array_merge(explode(",", $drh_shop), explode(",", $user)));

          foreach ($initiate as $k => $v) {
              $init[] = $k;
          }
          $init = implode(",", $init);

          //当前交子数量
          $array['jiaozi']['number'] = Common::summation(Common::db_count("user_integral", "", "drh_user_info", "id IN(" . $init . ")"), "user_integral");
          //当前交子质押
          $array['jiaozi']['pledge'] = Common::summation(Common::db_count("integral", "", "drh_integral_withdraw", "user_id IN(" . $init . ")"), "integral");
          //质押手续费
          $array['jiaozi']['charge_for_pledge'] = bcmul(Common::summation(Common::db_count("integral", "", "drh_integral_withdraw", "user_id IN(" . $user . ")"), "integral"), bcsub(100, $copulation['proportion_of_members']) / 100);
          //平台毛利   (质押手续费+白条累计盈利) 白条暂时为空
          $array['jiaozi']['margin'] = $array['jiaozi']['charge_for_pledge'];

          //区域合伙人 区域类型
          $arer_id = Common::db_count("user_id,type_lv", "", "drh_proxy", "area_id=" . $id)[0] ?? array();

          $partner = unserialize(Common::db_count("partner", "", "drh_parameter")[0]['partner']) ?? array();

          if ($arer_id !== array()) {
              switch ($arer_id['type_lv']) {
                  case 1:
                      $participation = $partner['area_profit'];
                      $array['district']['genre'] = "全国代理";
                      break;
                  case 2;
                      $participation = $partner['province_profit'];
                      $array['district']['genre'] = "省代理";
                      break;
                  case 3;
                      $participation = $partner['town_profit'];
                      $array['district']['genre'] = "市代";
                      break;
                  default;
                  $participation=0;
              }
          }else{
              $participation = 0;
          }
          //推荐荐该区域人ID
          if($arer_id !== array()){
              $array['district']['rict'] = Common::summation(Common::db_count("type_lv", "", "drh_proxy", "user_id=".$arer_id["type_lv"]) ?? array(), "type_lv");
          }else{
              $array['district']['rict'] = 0;
          }
          //现有推荐人奖励
          $user = Common::db_count("id,user_name,user_integral", "", "drh_user_info", "user_lv=1 AND city LIKE '%" . $regin['name'] . "%'");
          $shop_id = implode(",", Common::er_array(Common::db_count("shop_id", "", "drh_shop_city", " city LIKE '%" . $regin['name'] . "%'")));

          if ($shop_id == "") {
              $store = array();
              $turnover_id = -1;
          } else {
              $store = Common::db_count("id", "", "drh_shop", "id IN(" . $shop_id . ")");
              $turnover_id = implode(",", Common::er_array($store));
          }

          $referrer_award = unserialize(Common::db_count("merchant_and_commission", "", "drh_parameter")[0]['merchant_and_commission']) ?? array();

          $array['district']['referrer_award'] = bcmul(count($store) + count($user), $referrer_award['brokerage']);

          //合伙人收益比例
          $array['district']['earnings'] = $participation;
          //现有合伙人收益

          $array['district']['partner_income'] = bcmul(bcadd($array['commercial_tenant']['gross_margin'], $array['jiaozi']['margin']), $participation / 100);
          cache("details".$id, serialize($array));

        }
        return json(['code' => $this->t_code, 'msg' => 'OK',"data"=>$array]);
    }
    //供货商发货
    public function supplier($id,$freight_num){
        $order = Common::db_upload("drh_goods_order","freight_num={$freight_num},freight_method='已发货' where id={$id}");
        if($order == 1){
            return json(['code' =>$this->t_code, 'msg' => 'OK']);
        }else{
            return json(['code' =>$this->f_code, 'msg' => 'GG']);
        }
    }
    //供货商退货
    public function sales_return(){

    }
}